// JavaScript Document

function Game(){
	this.start = start;
	this.stop = stop;
}


var state= null;

function start(){
	state = 'start';
	var _speed = document.getElementById("txt_speed").value;
	var _size = document.getElementById("txt_size").value;
	//alert(_speed +':'+_size)
	
	var _letters = [];
	var _timerLettercreate;
	var _timerLettermove;
	
	//移除所有的Letter
	var _screenLetters = document.getElementsByTagName("div");
	
	for( i = 0 ; i < _screenLetters.length ; i ++){	
		var _screenLetter = _screenLetters[i];
		//_letters.splice( i , 1);
		_screenLetter.parentNode.removeChild(_screenLetter);
	}
	
	
	var moveLetter = function(){
		for( i = 0 ; i < _letters.length ; i ++){
			var _letter = _letters[i];
			var _top = (parseInt(_letter.style.top) + 10) ;
			_letter.style.top = _top + 'px';
			if((screen.width - _top) < 500){				
				_letters.splice( i , 1);
				_letter.parentNode.removeChild(_letter);
				//document.removeChild(_letter);
			}
		}
	}
	
	var createLetter = function(){
		if(state == 'stop'){
			clearInterval(_timerLettercreate);
			clearInterval(_timerLettermove);
		}
		var _random  = Math.random();
		var _hex=Math.round(_random*0x1000000);
		var _basecolor="00000".concat(_hex.toString(16));
		
		var _left =Math.round(_random * screen.width) -15;
		var _color = "#"+_basecolor.substr(_basecolor.length-6,6);
		var _top  = 35;
		//console.dir(document.getElementsByTagName("hr")[0]);
		var _code = Math.round((Math.random() * 24)) + 65;
		var _char = String.fromCharCode(_code);
		var _gameLetter = new Letter(_char, _top , _left , _color);
		//alert(_gameLetter.char.charCodeAt());
		var _letter = _gameLetter.letter();
		_letters.push(_letter);
		document.body.appendChild(_letter);
		
	}
	
	//设置时间任务
	_timerLettercreate =  setInterval(createLetter, (1000/_size ));
	
	_timerLettermove = setInterval(moveLetter , (1000/_speed))
	
}

function stop(){
	state = 'stop';
}

function Letter(char , top , left , color){
	this.char = char;
	this.color = color;
	this.top = top;
	this.left = left;
}

Letter.prototype.letter = function(){
	var _letter = document.createElement('div');
	_letter.style.top = this.top+'px';
	_letter.style.left = this.left +'px';
	_letter.style.position = 'absolute';
	var _font = '<font size="10" color = "'+this.color+'"> <b>'+this.char+'</b></font>';
	_letter.innerHTML = _font;
	return _letter;
}
